package com.hucc.api.service;

import com.hucc.api.domain.entity.Case;
import com.hucc.api.domain.entity.CaseWithBLOBs;
import com.hucc.api.domain.entity.InterfaceWithBLOBs;
import com.hucc.api.domain.entity.Project;
import com.hucc.api.domain.enums.CaseTypeEnum;
import com.hucc.api.domain.exceptions.BusinessException;
import com.hucc.api.domain.req.CaseReq;
import com.hucc.api.repository.CaseMapper;
import com.hucc.api.repository.InterfaceMapper;
import com.hucc.api.repository.ProjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class CaseService {
    @Autowired
    CaseMapper caseMapper;
    @Autowired
    ProjectMapper projectMapper;
    @Autowired
    InterfaceMapper interfaceMapper;


    public void add(CaseReq caseReq) throws BusinessException {
        if (caseReq == null) {
            throw new BusinessException("参数不能为空");
        }

        if (caseReq.getProjectId() == null) {
            throw new BusinessException("项目id不能为空");
        }

        if (caseReq.getPath() == null) {
            throw new BusinessException("接口路径不能为空");
        }

        Project project = projectMapper.selectByPrimaryKey(caseReq.getProjectId());
        if (project == null) {
            throw new BusinessException("项目不存在");
        }

        List<InterfaceWithBLOBs> interfaceWithBLOBs = interfaceMapper.getByProjectIdAndPath(caseReq.getProjectId(), caseReq.getPath());
        if (interfaceWithBLOBs.isEmpty()) {
            throw new BusinessException("接口不存在");
        }

        CaseWithBLOBs add = new CaseWithBLOBs();
        add.setProjectId(caseReq.getProjectId());
        add.setPath(caseReq.getPath());
        add.setType(CaseTypeEnum.DEFAULT.getType());
        add.setParam(caseReq.getParam());
        add.setRes(caseReq.getRes());
        add.setCreatetime(new Date());
        add.setUpdatetime(new Date());
        caseMapper.insertSelective(add);
    }
}
